package com.pocketsweet.ui.fragments;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.lidroid.xutils.ViewUtils;
import com.pocketsweet.C;
import com.pocketsweet.R;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.ui.TempMain;
import com.pocketsweet.ui.TempProfile;
import com.pocketsweet.ui.uilib.AutoListView;
import com.pocketsweet.ui.uilib.AutoListView.OnLoadListener;
import com.pocketsweet.ui.uilib.AutoListView.OnRefreshListener;
import com.pocketsweet.ui.uilib.MixListView;
import com.pocketsweet.ui.uilib.SlideView;
import com.pocketsweet.ui.uilib.SlideView.OnSlideListener;
import com.pocketsweet.ui.uilib.adapter.OnLineListAdapter;
import com.pocketsweet.ui.uilib.adapter.OnLineListAdapter.ViewHolder;
import com.pocketsweet.utils.ToolKits;

public class TempNewOnlineFragment extends Fragment implements
		OnRefreshListener, OnLoadListener, OnItemClickListener {

	private MixListView dropDownListView = null;
	private static OnLineListAdapter onLineListAdapter;
	public static List<MLUser> userList = new ArrayList<MLUser>();
	public static final int MORE_DATA_MAX_COUNT = 30; // 每页20个对象
	public static final int BEGIN_TO_LOADING = -1;
	public int skipDataCount = 0; // 忽略前N个对象
	private boolean isUpdateList = false; // 是否刷新列表
	private LinearLayout linBlank;
	public static boolean isSlide = false;
	final int RIGHT = 0;
	final int LEFT = 1;

	private boolean isClicked = false;

	public MLUser mlUser;
	public ViewHolder userHolder;
	public static OnSlideListener slideLister;
	private SlideView mLastSlideViewWithStatusOn;

	private LinearLayout llRandomCall;

	private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(TempMain.ACTION_CHOOSE_CHANGE)) {
				if (TempMain.choosedSex == 0) {
					TempMain.getInstance().getHeader()
							.setRightImg(R.drawable.icon_sex_all);
				} else if (TempMain.choosedSex == 1) {
					TempMain.getInstance().getHeader()
							.setRightImg(R.drawable.icon_sex_man);
				} else if (TempMain.choosedSex == 2) {
					TempMain.getInstance().getHeader()
							.setRightImg(R.drawable.icon_sex_female);
				}
				if (userList != null) {
					userList.clear();
				}
				onLineListAdapter.notifyDataSetChanged();
				dropDownListView.setAdapter(onLineListAdapter);
				getUserList(BEGIN_TO_LOADING);
			}
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_newonline, null);
		ViewUtils.inject(this, rootView);
		// initListview();
		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		dropDownListView = (MixListView) getView().findViewById(
				R.id.dropDownListview);
		linBlank = (LinearLayout) getView().findViewById(R.id.linBlank);

		onLineListAdapter = new OnLineListAdapter(getActivity(), userList);
		dropDownListView.setAdapter(onLineListAdapter);
		onLineListAdapter.notifyDataSetChanged();
		dropDownListView.setPageSize(MORE_DATA_MAX_COUNT);
		dropDownListView.setOnRefreshListener(this);
		dropDownListView.setOnLoadListener(this);
		dropDownListView.setOnItemClickListener(this);
		getUserList(BEGIN_TO_LOADING);// 首次进入app，加载数据
		// MLContext.deleteAll(); // 清空sharepreference
		slideLister = new OnSlideListener() { // 如果当前存在已经打开的SlideView，那么将其关闭

			@Override
			public void onSlide(View view, int status) {
				if (mLastSlideViewWithStatusOn != null
						&& mLastSlideViewWithStatusOn != view) {
					mLastSlideViewWithStatusOn.shrink();
				}

				if (status == SLIDE_STATUS_ON) {
					mLastSlideViewWithStatusOn = (SlideView) view;
				}

			}
		};
	}

	@Override
	public void onStart() {
		super.onStart();
		IntentFilter filter = new IntentFilter();
		filter.addAction(TempMain.ACTION_CHOOSE_CHANGE);
		getActivity().registerReceiver(receiver, filter);
	}

	@Override
	public void onResume() {
		isClicked = false;
		super.onResume();
		if (TempMain.needRefresh) {
			getUserList(AutoListView.REFRESH);
		}
		if (userHolder != null) {
			userHolder.update(mlUser);
			userHolder = null;
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(receiver);
	}

	/*
	 * 请求最近在线对象
	 */
	private void getUserList(final int what) {
		if (what != BEGIN_TO_LOADING) {
			isUpdateList = true; // 如果不是首次加载数据，则该动作为刷新

		} else {
			dropDownListView.setRefreshData(); // 初始化显示loading动态图片
		}
		if (userList == null || userList.size() <= 0 || isUpdateList) { // userList为空或者动作为下拉刷新、往下加载时请求leanCloud
			AVQuery<MLUser> query = new AVQuery<MLUser>("_User");
			skipDataCount = skipDataCount + MORE_DATA_MAX_COUNT; // 往下加载时忽略前一页
			if (what != AutoListView.LOAD) {
				skipDataCount = 0; // 刷新时不用忽略前面对象
				AVAnalytics.onEvent(getActivity(), "空闲恋人刷新");//埋点
			}
			// if (TempMain.choosedType == C.USER_TYPE_RECOMMENDED) {//筛选是否为编辑推荐
			query.whereNotEqualTo(MLUser.TYPE, C.USER_TYPE_NORMAL);
			// }
			query.whereNotEqualTo(MLUser.STATUS, C.USER_STATUS_DISABLE);
			query.whereNotEqualTo(MLUser.STATUS, C.USER_STATUS_BADINFO);

			if (TempMain.choosedSex != 0) {
				if (TempMain.choosedSex == 1) { // 若选择男性
					query.whereEqualTo(MLUser.GENDER, 1);
				} else if (TempMain.choosedSex == 2) {
					query.whereEqualTo(MLUser.GENDER, 2);

				}
			}
			linBlank.setVisibility(View.GONE);
			query.setSkip(skipDataCount); // 忽略前N个
			query.limit(MORE_DATA_MAX_COUNT); // 设置每页对象个数
			query.orderByDescending(MLUser.LASTLOGIN);
			query.whereEqualTo("isUserInited", 1); // 只显示 认证完成的用户
			// query.whereNotEqualTo("objectId", UserService.getCurrentUser()
			// .getObjectId());// 不用显示自己
			query.findInBackground(new FindCallback<MLUser>() {
				@Override
				public void done(List<MLUser> users, AVException e) {
					// loading.dismiss();
					// 取出参与的人
					if (e == null) {
						if (users.size() != 0) {
							switch (what) {
							case AutoListView.REFRESH: // 下拉刷新时直接重新获取数据
								userList = users;
								dropDownListView.onRefreshComplete();
								// onLineListAdapter.setDatas(userList);
								break;
							case AutoListView.LOAD: // 加载更多时把新获取的数据添加到list列表
								dropDownListView.onLoadComplete();
								userList.addAll(users);
								break;
							case BEGIN_TO_LOADING: // Application无数据时首次加载，即重新获取数据
								userList = users;
								dropDownListView.onRefreshComplete();
								// onLineListAdapter.setDatas(userList);
								break;
							}
							linBlank.setVisibility(View.GONE);
							dropDownListView.setResultSize(userList.size());
							onLineListAdapter.setDatas(userList);
							onLineListAdapter.notifyDataSetChanged();
							isUpdateList = false; // 刷新完毕，设为false
						} else if (users.size() == 0) {
							if (what != AutoListView.LOAD) {
								ToolKits.toast(getActivity(), "无搜索结果");
							}
							dropDownListView.setNoData();
						}
					} else {
						// error ，继续重新获取
						linBlank.setVisibility(View.VISIBLE);
						getUserList(BEGIN_TO_LOADING);
					}
				}
			});
		} else {
		}
	}

	@Override
	public void onLoad() {
		getUserList(AutoListView.LOAD);
	}

	@Override
	public void onRefresh() {
		getUserList(AutoListView.REFRESH);
		dropDownListView.setOnRefreshListener(this);

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (position - 1 < 0 || onLineListAdapter.getCount() <= 0) {
			return;
		}
		mlUser = (MLUser) onLineListAdapter.getItem(position - 1);
		if (mlUser.getType() == C.USER_TYPE_NORMAL) {
			isSlide = false;
		}
		if (isSlide == true && mlUser.slide.isScroll == true) { // 如果正在滑动，不触发点击事件
			return;
		}
		userHolder = onLineListAdapter.new ViewHolder(view);

		String selectedUserId = ((MLUser) onLineListAdapter
				.getItem(position - 1)).getObjectId();
		// String selectedUserId = ((MLUser) onLineListAdapter
		// .getItem(position - 2)).getObjectId();
		// String likeCount = ((TextView) view.findViewById(R.id.tvLike))
		// .getText().toString();
		// boolean isLiked = MLContext.getUserLikeID(selectedUserId) == 0 ?
		// false
		// : true;
		Intent intent;
		intent = new Intent(getActivity(), TempProfile.class);
		// Log.e("String", selectedUserId + "  " + likeCount);
		intent.putExtra("userId", selectedUserId);
		intent.putExtra("nickname", mlUser.getNickname());
		// intent.putExtra("position", String.valueOf(position - 2));
		getActivity().startActivity(intent);

		// }

	}
}